import React, { useState, useRef } from 'react';
import axios from 'axios';
import { toast } from 'react-toastify';
import Modal from './Modal';
import { FaCopy } from 'react-icons/fa';

function ShareModal({ isOpen, onClose, document }) {
  const [shareLink, setShareLink] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [isCopying, setIsCopying] = useState(false);
  const shareLinkInputRef = useRef(null);
  
  // 生成分享链接
  const generateShareLink = async () => {
    try {
      setIsGenerating(true);
      console.log('正在为文档生成分享链接:', document.id);
      const response = await axios.post(`/api/docs/${document.id}/share`);
      console.log('分享链接生成成功:', response.data);
      setShareLink(response.data.shareLink);
    } catch (error) {
      console.error('生成分享链接失败:', error);
      if (error.response) {
        console.error('错误详情:', error.response.data);
      }
      toast.error('生成分享链接失败');
    } finally {
      setIsGenerating(false);
    }
  };
  
  // 复制分享链接
  const copyShareLink = async () => {
    if (!shareLink) return;
    
    setIsCopying(true);
    
    try {
      // 优先使用现代Clipboard API
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(shareLink);
        toast.success('链接已复制到剪贴板');
      } else {
        // 回退到传统方法
        const textArea = document.createElement('textarea');
        textArea.value = shareLink;
        
        // 设置样式使元素不可见
        textArea.style.position = 'fixed';
        textArea.style.top = '0';
        textArea.style.left = '0';
        textArea.style.width = '2em';
        textArea.style.height = '2em';
        textArea.style.padding = '0';
        textArea.style.border = 'none';
        textArea.style.outline = 'none';
        textArea.style.boxShadow = 'none';
        textArea.style.background = 'transparent';
        
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        // 尝试执行复制命令
        const successful = document.execCommand('copy');
        document.body.removeChild(textArea);
        
        if (successful) {
          toast.success('链接已复制到剪贴板');
        } else {
          // 如果都失败，提示用户手动复制
          if (shareLinkInputRef.current) {
            shareLinkInputRef.current.select();
          }
          toast.warning('请手动选择链接并复制');
        }
      }
    } catch (error) {
      console.error('复制失败:', error);
      // 选择文本，方便用户手动复制
      if (shareLinkInputRef.current) {
        shareLinkInputRef.current.focus();
        shareLinkInputRef.current.select();
      }
      toast.warning('自动复制失败，请手动选择并复制链接');
    } finally {
      setIsCopying(false);
    }
  };
  
  // 如果modal打开并且还没有分享链接，则生成一个
  React.useEffect(() => {
    if (isOpen && document && !shareLink) {
      generateShareLink();
    }
  }, [isOpen, document]);
  
  if (!document) return null;
  
  return (
    <Modal 
      isOpen={isOpen} 
      onClose={onClose}
      title="分享文档"
    >
      <div className="share-modal-content">
        <div className="share-link-section">
          <h3>分享链接</h3>
          {isGenerating ? (
            <div className="generating-container">
              <p className="generating-message">正在生成分享链接...</p>
              <div className="loading-spinner small"></div>
            </div>
          ) : (
            <>
              <p className="share-info">任何拥有此链接的人都可以查看此文档内容</p>
              <div className="share-link-container">
                <input 
                  type="text"
                  value={shareLink}
                  readOnly
                  className="share-link-input"
                  ref={shareLinkInputRef}
                  onClick={(e) => e.target.select()}
                />
                <button 
                  className="copy-link-btn"
                  onClick={copyShareLink}
                  title="复制链接"
                  disabled={!shareLink || isCopying}
                >
                  <FaCopy />
                </button>
              </div>
              <p className="manual-copy-hint">
                如果无法自动复制，请点击链接框选择文本，然后按Ctrl+C(或Command+C)手动复制
              </p>
            </>
          )}
        </div>
        
        <div className="modal-actions">
          <button 
            className="btn btn-secondary" 
            onClick={onClose}
          >
            关闭
          </button>
          <button 
            className="btn btn-primary" 
            onClick={copyShareLink}
            disabled={!shareLink || isGenerating || isCopying}
          >
            {isCopying ? '复制中...' : '复制链接'}
          </button>
        </div>
      </div>
    </Modal>
  );
}

export default ShareModal; 